package com.vineetmanohar.nitrogen;

import java.io.File;
import java.io.IOException;
import java.util.Collection;

import org.apache.commons.io.FileUtils;
import org.testng.Assert;

public class NitrogenTestUtils {
	public static File getDataFile(String fileName) {
		return new File("src" + File.separator + "test" + File.separator
				+ "data" + File.separator + fileName);
	}

	public static Model getSampleModel(String name) throws IOException {
		return ModelFactory.parseModelFile(NitrogenTestUtils.getDataFile(name));

	}

	public static Object[] createSample(String setNo) {
		File modelFile = getDataFile("model" + setNo + ".xml");
		File inputFile = getDataFile("input" + setNo + ".txt");
		File expectedOutputFile = getDataFile("expectedOutput" + setNo + ".txt");
		return new Object[] { modelFile, inputFile, expectedOutputFile };
	}

	public static File getTmpNitrogenDir() {
		File tmpDir = new File(System.getProperty("user.home"));
		File tmpNitrogenDir = new File(tmpDir, ".nitrogen" + File.separator
				+ "tmp" + File.separator + "unittest");
		return tmpNitrogenDir;
	}

	public static File getCleanTmpNitrogenDir() {
		File tmpNitrogenDir = getTmpNitrogenDir();
		try {
			FileUtils.cleanDirectory(tmpNitrogenDir);
		} catch (IOException e) {
			throw new NitrogenException("Could not clean tmp nitrogen dir: "
					+ tmpNitrogenDir.getAbsolutePath(), e);
		}
		return tmpNitrogenDir;
	}

	public static File getTmpOutputNitrogenDir() {
		return new File(getTmpNitrogenDir(), "output");
	}

	public static File getCleanTmpOutputNitrogenDir() {
		File tmp = getTmpOutputNitrogenDir();
		try {
			FileUtils.forceMkdir(tmp);
		} catch (IOException e) {
			throw new NitrogenException("Unable to create directory "
					+ tmp.getAbsolutePath() + ", check permissions", e);
		}

		return tmp;
	}

	public static void compareDirs(File actualDir, File expectedDir)
			throws IOException {
		@SuppressWarnings("unchecked")
		Collection<File> actualFiles = FileUtils.listFiles(actualDir, null,
				true);

		// get relative path
		for (File actualFile : actualFiles) {
			File expectedFile = NitrogenUtils.getProjectedPath(actualFile,
					actualDir, expectedDir);

			compareFile(actualFile, expectedFile);
		}
	}

	private static void compareFile(File actualFile, File expectedFile) throws IOException {
		Assert.assertNotNull(actualFile);
		Assert.assertNotNull(expectedFile, "File expected but not found "
				+ expectedFile);
		Assert.assertEquals(
				FileUtils.readFileToString(actualFile),
				FileUtils.readFileToString(expectedFile),
				"File contents don't match expectation: "
						+ expectedFile.getAbsolutePath());
	}
}